package com.rivues.module.platform.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;

public class UserInterceptorHandler extends HandlerInterceptorAdapter {
	private String exclude  ;
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}
	
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView view) throws Exception {
		if(view!=null){
			view.addObject("user", SecurityUtils.getSubject().getSession().getAttribute(RivuDataContext.USER_SESSION_NAME)) ;
			HandlerMethod  handlerMethod = (HandlerMethod ) arg2 ;
			RequestMapping obj = handlerMethod.getMethod().getAnnotation(RequestMapping.class) ;
			view.addObject("subtype", obj.subtype()) ;
			view.addObject("mantype", obj.type()) ;
			
		}
	}
	@Override  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
        String uri = request.getRequestURI();  
        boolean filter = false; 
        for (String s : exclude.split(",")) {  
            if (uri.matches(s)) {  
            	filter = true;  
                break;  
            }  
        }  
        if(!filter){
        	filter = SecurityUtils.getSubject().getSession().getAttribute(RivuDataContext.USER_SESSION_NAME)!=null ;
        }
        if(!filter && uri.indexOf("/",1)>=0){
        	response.sendRedirect("/");
        	/**
        	 * 记录Refer信息
        	 */
        	if(uri.indexOf("logout") < 0){
	        	if(request.getSession().getAttribute(RivuDataContext.REFER_STR)!=null){
	        		request.getSession().removeAttribute(RivuDataContext.REFER_STR);
	        	}
	        	request.getSession().setAttribute(RivuDataContext.REFER_STR, uri);
        	}
        }
        return filter ;  
    }
	public String getExclude() {
		return exclude;
	}
	public void setExclude(String exclude) {
		this.exclude = exclude;
	}  
}
